#include "Sync.h"

uint32_t            gloabal_time=0; //全局时钟（x10ms)
uint16_t            heart_time_pos=0;

//*******************************************************************************
// 心跳时刻表：根据群组位确定心跳发送时间，96*2灯（16群 3组/群）
//            每个灯200ms(单位10ms)发送窗口，周期40S
//*******************************************************************************
uint16_t  tb_heart_time_group_base[16]={0,240,480,720,960,1200,1440,1680,1920,
                                        2160,2400,2640,2880,3120,3360,3600};     //每个群首的灯心跳时刻，单位ms

uint16_t  tb_heart_time_light_offset[3][4]={{0,   20,  40,  60  },
                                            {80,  100, 120, 140 },
                                            {160, 180, 200, 220 }};              //每个群分3组，每组4个灯，在本组内的心跳偏移

//*******************************************************************************
// update_heart_time_intval
//            根据群组位获取心跳时刻。
//*******************************************************************************
void update_heart_time_intval(uint8_t crowd/*群*/, uint8_t group/*组*/, uint8_t tag/*位*/)
{
   uint16_t base,offset;
   base  = tb_heart_time_group_base[crowd-1];
   offset= tb_heart_time_light_offset[group-1][tag-1];
   heart_time_pos = base+offset;
}

//*******************************************************************************
// heart_time_hit
//            到达心跳时刻
//*******************************************************************************
uint8_t heart_time_hit(uint16_t time)
{
   return (time==heart_time_pos);
}

//*******************************************************************************
// 全局时钟,时钟信息保存在noninit寄存器，重启不丢失
//*******************************************************************************
uint32_t GLBO_Timer_INC(uint8_t _10ms)
{
  uint32_t ret;
  gloabal_time += _10ms;
  RTC_WriteBackupRegister(0, gloabal_time>>16);
  RTC_WriteBackupRegister(1, gloabal_time);
  ret = (uint32_t)(gloabal_time%4000);                                                       //40S
  return ret;
}

uint32_t GLBO_Timer_DEC(uint8_t _10ms)
{
  uint32_t ret;
  gloabal_time -= _10ms;
  RTC_WriteBackupRegister(0, gloabal_time>>16);
  RTC_WriteBackupRegister(1, gloabal_time);
  ret = (uint32_t)(gloabal_time%4000);                                                       //40S
  return ret;
}

uint32_t GLBO_Timer_SAVE(uint32_t time)
{
  uint32_t ret;
  gloabal_time = time;
  RTC_WriteBackupRegister(0, time>>16);
  RTC_WriteBackupRegister(1, time);
  ret =  (uint32_t)(gloabal_time%4000);                                                
  return ret;
}

void GLBO_Timer_RELOAD()
{
  uint16_t gt_h,gt_l;
  gt_h = RTC_ReadBackupRegister(0);
  gt_l = RTC_ReadBackupRegister(1);
  gloabal_time = (gt_h<<16)|gt_l;
}